<template>
  <v-dialog-layout
    title="分配权限"
    width="1100px"
    v-model:visible="visible"
    @confirm="formAdd.onSubmit()"
    @cancel="cancel"
  >
    <v-form-layout
      ref="formAdd"
      style="min-height: 500px"
      v-model:form-data="formData"
      @validateSuccess="validateSuccess"
    >
      <v-row-layout>
        <a-col :span="12">
          <a-form-item label="应用权限" name="roleName" placeholder="请输入应用名称">
            <a-checkbox-group v-model:value="formData.appList" @change="selectAppChange">
              <div class="app-list">
                <template v-for="item in apps" :key="item.id">
                  <div class="column-list-item">
                    <a-checkbox :value="item.id"></a-checkbox>
                    <span class="column-name">{{ item.name }}</span>
                  </div>
                </template>
              </div>
            </a-checkbox-group>
          </a-form-item>
          <a-form-item label="菜单权限" name="appCode" placeholder="请输入应用编号">
            <div class="left-menu">
              <a-tree
                checkable
                blockNode
                :tree-data="menus"
                :replaceFields="{ children: 'children', title: 'title', key: 'id' }"
                v-model:expandedKeys="expandedKeys"
                v-model:selectedKeys="selectedKeys"
                v-model:checkedKeys="checkedKeys"
                @check="onBusinessSelectChange"
              ></a-tree>
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="按钮权限" name="enabled">
            <div class="right-btn">
              <a-checkbox-group v-model:value="formData.btnList" @change="selectBtnChange">
                <div class="app-list">
                  <template v-for="item in btns" :key="item.id">
                    <div class="column-list-item">
                      <a-checkbox :value="item.id"></a-checkbox>
                      <span class="column-name">{{ item.menuInfo.title }}-{{ item.btnName }}</span>
                    </div>
                  </template>
                </div>
              </a-checkbox-group>
            </div>
          </a-form-item>
        </a-col>
      </v-row-layout>
    </v-form-layout>
  </v-dialog-layout>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, reactive } from 'vue'
import useCurrentInstance from 'lib-utils/vueInstance'
const { proxy } = useCurrentInstance()

const props = withDefaults(defineProps<{
  visible: boolean,
  roleId: string | number | null
}>(), {
  visible: false
})
const emit = defineEmits(['update:visible', 'close'])

const formAdd = ref()
const menus = ref([])
const apps:any = ref([])
const btns:any = ref([])
const expandedKeys = ref([])
const selectedKeys = ref([])
const checkedKeys = ref([])
// 没有全选的父级菜单id
const halfCheckMenus = ref([])
const formData:{
  appList: any[],
  menuList: any[],
  btnList: any[]
} = reactive({
  appList: [],
  menuList: [],
  btnList: []
});
watch(selectedKeys, () => {
  console.log(selectedKeys.value, 'selectedKeys---')
});

watch(checkedKeys, () => {
  getAllBtns({
    menuIds: JSON.stringify(checkedKeys.value)
  })
});

onMounted(() => {
  getInitPermission()
  getAllApps()
})
// 获取当前用户已经分配的权限信息，回显到页面
const getInitPermission = () => {
  proxy.$http.get(proxy.$api.role.permissionList, {
    roleId: props.roleId
  }).then((res:any) => {
    formData.appList = res.appList.map((item:any) => { return item.appId })
    formData.btnList = res.btnList.map((item:any) => { return item.btnId })
    checkedKeys.value = res.menuList.map((item:any) => { return item.menuId })
    getAllMenus({
      appIds: JSON.stringify(formData.appList)
    })
    getAllBtns({
      menuIds: JSON.stringify(checkedKeys.value)
    })
  })
}

const getAllMenus = (params) => {
  proxy.$http.get(proxy.$api.menu.listTree, params).then((res:any) => {
    menus.value = res
  })
}

const getAllApps = () => {
  proxy.$http.get(proxy.$api.application.listAll).then((res:any) => {
    apps.value = res
  })
}

const getAllBtns = (params) => {
  proxy.$http.get(proxy.$api.btn.listAll, params).then((res:any) => {
    btns.value = res
    formData.btnList = btns.value.map((item:any) => {
      return item.id
    })
  })
}

const selectAppChange = (e:any) => {
  getAllMenus({
    appIds: JSON.stringify(e)
  })
}

const selectBtnChange = () => {

}

const onBusinessSelectChange = (selectedKeys, info) => {
  console.log(info.halfCheckedKeys)
  halfCheckMenus.value = info.halfCheckedKeys
}

const validateSuccess = () => {
  let params = {
    roleId: props.roleId,
    btnList: formData.btnList.map(item => {
      return { roleId: props.roleId, btnId: item }
    }),
    menuList: checkedKeys.value.map(item => {
      return { roleId: props.roleId, menuId: item, halfCheck: 0 }
    }).concat(halfCheckMenus.value.map(item => {
      return { roleId: props.roleId, menuId: item, halfCheck: 1 }
    })),
    appList: formData.appList.map(item => {
      return { roleId: props.roleId, appId: item }
    })
  }
  proxy.$http.post(proxy.$api.role.distribute, params).then(() => {
    proxy.$vMessage.success('分配成功')
    emit('update:visible', false)
    emit('close', false)
  })
}

const cancel = () => {
  emit('update:visible', false)
}
</script>

<style lang="less" scoped>
.app-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  .column-list-item {
    margin-right: 26px;
    .column-name {
      margin-left: 10px;
    }
  }
}
.left-menu {
  height: 480px;
  overflow-y: auto;
}
.right-btn {
  height: 540px;
  padding: 6px 10px;
  overflow-y: auto;
}

.left-menu:before,
.right-btn:before {
  position: absolute;
  left: -2px;
  top: -2px;
  right: -2px;
  bottom: -2px;
  content: "";
  border: 1px solid #f2f2f2;
  border-radius: 4px;
  overflow: visible;
}
</style>